<template>
  <view class="order-detail-page">
    <view class="order-status-header" :class="'status-' + orderInfo.orderState">
      <text class="status-text">{{ getOrderStatusText(orderInfo.orderState) }}</text>
      <text class="status-desc" v-if="orderInfo.orderState === 10">请在预约时间内前往场地核销</text>
    </view>

    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单编号: </text>
        <text class="value">{{ orderInfo.orderNo }}</text>
      </view>

      <view class="info-item">
        <text class="label">下单时间: </text>
        <text class="value">{{ orderInfo.createTime }}</text>
      </view>

      <view class="info-item">
        <text class="label">球桌: </text>
        <text class="value">{{ orderInfo.productName }}</text>
      </view>

      <view class="info-item">
        <text class="label">预约日期: </text>
        <text class="value">{{ orderInfo.date }} {{ orderInfo.week }}</text>
      </view>

      <view class="info-item">
        <text class="label">预约时间: </text>
        <text class="value">{{ orderInfo.timeSlot }}</text>
      </view>

      <view class="info-item">
        <text class="label">时长: </text>
        <text class="value">{{ orderInfo.duration }}时</text>
      </view>
    </view>

    <view class="payment-info-section">
      <view class="section-title">费用明细</view>
      <view class="info-item">
        <text class="label">单价: </text>
        <text class="value">¥{{ orderInfo.price }}/小时</text>
      </view>

      <view class="info-item">
        <text class="label">时长: </text>
        <text class="value">{{ orderInfo.duration }}小时</text>
      </view>

      <view class="info-item total-row">
        <text class="label">总计: </text>
        <text class="value total-price">¥{{ orderInfo.orderPayPrice }}</text>
      </view>
    </view>

    <!-- 时间段选择和二维码展示 -->
    <view class="verification-section"
      v-if="orderInfo.orderState === 10 && orderInfo.priceDateTimeRangeVOList && orderInfo.priceDateTimeRangeVOList.length > 0">
      <view class="section-title">核销二维码</view>

      <!-- 时间段选择器 -->
      <view class="time-slot-selector" v-if="orderInfo.priceDateTimeRangeVOList.length > 1">
        <scroll-view class="time-slot-scroll" scroll-x>
          <view class="time-slot-list">
            <view v-for="timeSlot in orderInfo.priceDateTimeRangeVOList" :key="timeSlot.id"
              class="time-slot-item" :class="{ active: selectedTimeslot.id === timeSlot.id }"
              @click="selectTimeSlot(timeSlot)">
              {{ formatTimeRange(timeSlot.startTime, timeSlot.endTime) }}
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 二维码展示 -->
      <view class="qrcode-container">
        <view class="selected-time-slot" v-if="selectedTimeslot">
          {{ formatTimeRange(selectedTimeslot.startTime, selectedTimeslot.endTime) }}
        </view>
        <image class="qrcode-image" :src="selectedTimeslot?.verificationQRCode" mode="aspectFit"
          v-if="selectedTimeslot?.isExpired"></image>
        <view v-else class="expired-tip">
          <text class="expired-text">该时间段已过期，无法生成二维码</text>
        </view>
        <text class="qrcode-tip" v-if="selectedTimeslot?.isExpired">请问工作人员出示此二维码进行核销</text>
      </view>
    </view>

    <view class="order-action-section">
      <view v-if="orderInfo.orderState == 1" class="action-buttons">
        <button class="action-button secondary-button" @click="btncancelOrder">
          取消订单
        </button>
        <button class="action-button primary-button" @click="payOrder">
          去付款
        </button>
      </view>
      <button v-else-if="orderInfo.orderState == 10" class="action-button secondary-button" @click="applyRefund">
        申请退款
      </button>
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  computed,
  onUnmounted
} from 'vue';
import {
  onLoad
} from '@dcloudio/uni-app';
import {
  getOrderDetails,
  getOrderVerificationCode,
  cancelOrder
} from '@/services/order.js';
import {
  formatDateTimeRange
} from '@/utils/date.js';

// 订单信息
const orderInfo = ref({});

// 选中的时间段
const selectedTimeslot = ref(null);

// 二维码刷新定时器
const qrRefreshTimer = ref(null);

// 页面加载
onLoad((options) => {
  if (options.orderNo) {
    loadOrderDetail(options.orderNo);
  }
});

// 页面卸载时清除定时器
onUnmounted(() => {
  clearQRCodeRefreshTimer();
});

// 加载订单详情
const loadOrderDetail = async (orderNo) => {
  try {
    const res = await getOrderDetails(orderNo);
    if (res.data) {
      const newOrders = res.data;
      // 处理订单的日期和时间信息
      if (newOrders.priceDateTimeRangeVOList) {
        const {
          formattedDate,
          formattedTimeSlot
        } = formatDateTimeRange(newOrders.priceDateTimeRangeVOList);
        newOrders.date = formattedDate.split(' ')[0];
        newOrders.week = formattedDate.split(' ')[1];
        newOrders.timeSlot = formattedTimeSlot;
        newOrders.duration = newOrders.priceDateTimeRangeVOList.length;
        newOrders.price = newOrders.priceDateTimeRangeVOList[0].price;
        // 初始化选中的时间段为第一个时间段
        if (newOrders.priceDateTimeRangeVOList.length > 0) {
          selectedTimeslot.value = newOrders.priceDateTimeRangeVOList[0];
          // 开始刷新二维码
          startQRCodeRefresh();
        }
      }
      orderInfo.value = newOrders;
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    });
  }
};

/* 获取订单状态文本 */
const getOrderStatusText = (state) => {
  const statusMap = {
    1: '待支付',
    10: '待核销',
    25: '已完成',
    20: '已退款',
    5: '已取消'
  };
  return statusMap[state] || '未知状态';
};

/* 支付订单 */
const payOrder = () => {
  uni.navigateTo({
    url: `/pages/list/payDetail?orderNo=${orderInfo.value.orderNo}`
  })
};

/* 申请退款 */
const applyRefund = () => {
  uni.showModal({
    title: '申请退款',
    content: '确定要申请退款吗？',
    success: function (res) {
      if (res.confirm) {
        uni.showToast({
          title: '已申请退款',
          icon: 'success'
        });
        // 实际项目中应该调用退款API
        orderInfo.value.state = 20;
      }
    }
  });
};

// 取消订单
const btncancelOrder = () => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消该订单吗？',
    success: async function (res) {
      const data = await cancelOrder(orderInfo.value.orderNo);
      if (data.code == 200) {
        uni.showToast({
          title: '取消成功',
          icon: 'success'
        });
        loadOrderDetail(orderInfo.value.orderNo);
      } else {
        uni.showToast({
          title: '取消失败',
          icon: 'none'
        });
      }
    },
  });
};

// 选择时间段
const selectTimeSlot = (timeSlot) => {
  selectedTimeslot.value = timeSlot;
  // 选中时间段后刷新该时间段的二维码
  startQRCodeRefresh();
};

// 开始刷新二维码
const startQRCodeRefresh = () => {
  // 清除已存在的定时器
  clearQRCodeRefreshTimer();
  // 刷新二维码
  refreshQRCode();
  qrRefreshTimer.value = setInterval(() => {
    refreshQRCode();
  }, 10000);
};

// 清除二维码刷新定时器
const clearQRCodeRefreshTimer = () => {
  if (qrRefreshTimer.value) {
    clearInterval(qrRefreshTimer.value);
    qrRefreshTimer.value = null;
  }
};

// 刷新二维码（可刷新指定时间段或当前选中的时间段）
const refreshQRCode = async () => {
  if (!selectedTimeslot.value) return;
  try {
    // 调用API获取当前选中时间段的二维码
    const res = await getOrderVerificationCode(selectedTimeslot.value.id);
    if (res.code == 200) {
      selectedTimeslot.value.verificationQRCode = res.data;
      selectedTimeslot.value.isExpired = false;
      return;
    } else if (res.code == 500) {
      // 时间段已过期，不显示二维码
      selectedTimeslot.value.verificationQRCode = '';
      selectedTimeslot.value.isExpired = true;
      clearQRCodeRefreshTimer();
      return;
    }
  } catch (error) {
    console.error('获取二维码失败:', error);
    selectedTimeslot.value.verificationQRCode = '';
    selectedTimeslot.value.isExpired = false;
  }
};

// 格式化时间范围
const formatTimeRange = (startTime, endTime) => {
  const start = startTime.split(' ')[1].substring(0, 5);
  const end = endTime.split(' ')[1].substring(0, 5);
  return `${start}-${end}`;
};
</script>

<style lang="scss">
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 15px 20px;
}

.order-status-header {
  text-align: center;
  padding: 30px 0;
  margin-bottom: 15px;
  border-radius: 8px;
  position: relative;
  overflow: hidden;

  &:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.15);
    z-index: 1;
  }

  &.status-1 {
    /* 待支付 */
    background: linear-gradient(135deg, #ff9990, #ffcc00);
  }

  &.status-10 {
    /* 待核销 */
    background: linear-gradient(135deg, #165dff, #3399ff);
  }

  &.status-25 {
    /* 已完成 */
    background: linear-gradient(135deg, #00cc66, #00ff99);
  }

  &.status-20 {
    /* 已退款 */
    background: linear-gradient(135deg, #999999, #cccccc);
  }

  &.status-5 {
    /* 已取消 */
    background: linear-gradient(135deg, #999999, #cccccc);
  }

  .status-text {
    font-size: 22px;
    font-weight: bold;
    color: #fff;
    position: relative;
    z-index: 2;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .status-desc {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);
    position: relative;
    z-index: 2;
    margin-top: 8px;
    display: block;
  }
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eeeeee;
}

.order-info-section,
.payment-info-section,
.verification-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  margin-bottom: 12px;

  &.total-row {
    margin-top: 18px;
    padding-top: 18px;
    border-top: 1px dashed #f6fe76;
  }
}

.label {
  flex: 1;
  font-size: 14px;
  color: #666;
}

.value {
  flex: 2;
  font-size: 14px;
  color: #333;
  text-align: right;

  &.total-price {
    color: #ff6668;
    font-size: 16px;
    font-weight: bold;
  }
}

/* 时间段选择和二维码展示样式 */
.time-slot-selector {
  margin-bottom: 20px;

  .time-slot-scroll {
    white-space: nowrap;
    width: 100%;

    .time-slot-list {
      display: inline-block;
      min-width: 100%;
      padding: 8rpx 0;

      .time-slot-item {
        display: inline-block;
        padding: 8px 15px;
        margin-right: 10px;
        background-color: #FFFFFF;
        border-radius: 20px;
        font-size: 14px;
        color: #666;
        cursor: pointer;

        &.active {
          background-color: #1554ff;
          color: #ffffff;
        }
      }
    }
  }
}

.qrcode-container {
  text-align: center;

  .selected-time-slot {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }

  .qrcode-image {
    width: 200px;
    height: 200px;
    margin: 0 auto 15px;
  }

  .expired-tip {
    font-size: 14px;
    color: #999;
    display: block;
    margin-bottom: 15px;

    .expired-text {
      font-weight: bold;
    }
  }

  .qrcode-tip {
    font-size: 14px;
    color: #999;
    display: block;
  }
}

.order-action-section {
  padding: 15px 0;

  .action-buttons {
    display: flex;
    gap: 10px;
  }

  .action-button {
    flex: 1;
    width: 100%;
    padding: 12px 0;
    font-size: 16px;
    border-radius: 6px;
    border: none;

    &.primary-button {
      background-color: #165dff;
      color: #fff;
    }

    &.secondary-button {
      background-color: #fff;
      color: #165dff;
      border: 1px solid #165dff;
    }

    &.disabled-button {
      background-color: #f5f5f5;
      color: #999;
    }
  }
}
</style>